package com.hilaver.dzmis.web.servlet.accesscontrol;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.sql.Blob;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.hibernate.Hibernate;

import com.hilaver.dzmis.Constants;
import com.hilaver.dzmis.accesscontrol.AcUser;
import com.hilaver.dzmis.service.impl.AcUserServiceImpl;
import com.hilaver.dzmis.util.StringUtils;
import com.hilaver.dzmis.web.servlet.AbstractBaseServlet;

public class AcUserServlet extends AbstractBaseServlet{
	
	public final static int ACTION_IS_USER_NAME_EXIST = 100;
	
	
	public final static int ACTION_EDIT_AC_USER_ACTION = 200;
	
	public final static int ACTION_GET_AC_USER_ACTION_FILTERS = 201;
	
	public final static int ACTION_DELETE_AC_USER_ACTION = 202;
	
	private static final long serialVersionUID = 1L;

	public AcUserServlet(){
		this.fullName = AcUser.class.getName();
		this.simpleName = AcUser.class.getSimpleName();
	}
	
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter writer = response.getWriter();
		try {
			
			String outputStr = execute(request);
			if (this.action == ACTION_EDIT) {
				response.setContentType(Constants.HTML_RESPONSE_TYPE);
			}
			writer.write(outputStr);
		} catch (Exception e) {
			writer.print(e.getMessage());
			e.printStackTrace();
		}
		writer.close();
	}

	protected String execute(HttpServletRequest request) throws Exception {
		this.setAction(request);

		AcUserServiceImpl acUserService = new AcUserServiceImpl();
		acUserService.setLocale((Locale) request.getSession()
				.getAttribute(Constants.SESSION_LOCALE));
		acUserService.setRealFileDir(AbstractBaseServlet.UPLOAD_TEMP_REAL_DIR);
		this.setAcUser(request, acUserService);
		Method method = null;
		String rtn = "";

		switch (this.action) {
		case ACTOIN_GET_ALL_PAGINATION: // "getAllPagination";
			this.setPaginationParam(request);
			method = acUserService.getClass().getMethod("getAllPagination",
					new Class[] { int.class, String.class, String.class });// int
			// page,
			// String
			// sort,
			// String
			// order
			rtn = (String) method.invoke(acUserService, new Object[] { this.page,
					this.sort, this.dir });
			break;
		case ACTION_EDIT: // "edit";
			this.fillObj(request);
			method = acUserService.getClass().getMethod("edit",
					new Class[] { Object.class });
			rtn = (String) method.invoke(acUserService, new Object[] { this.obj });
			break;
		case ACTION_DELETE: // "delete";
			this.setId(request);
			method = acUserService.getClass().getMethod("delete",
					new Class[] { int.class });
			rtn = (String) method.invoke(acUserService, new Object[] { this.id });
			break;
		case ACTION_GET: // "get one"
			this.setId(request);
			method = acUserService.getClass().getMethod("get",
					new Class[] { int.class });
			rtn = (String) method.invoke(acUserService, new Object[] { this.id });
			break;
		case ACTION_GET_WITH_DESCRIPTION:
			this.setId(request);
			rtn = acUserService.getWithDescription(this.id);
			break;
		case ACTION_GET_ALL_PAGINATION_FILTER: // "getAllPagination filter"
			this.setPaginationParam(request);
			this.setFilterParam(request);
			method = acUserService.getClass().getMethod(
					"getAllPagination",
					new Class[] { int.class, String.class, String.class,
							String[].class });// int page, String sort, String
			// order
			rtn = (String) method.invoke(acUserService, new Object[] { this.page,
					this.sort, this.dir, this.filters });
			break;
		case ACTION_GET_ALL:
			this.setPaginationParam(request);
			method = acUserService.getClass().getMethod("getAll",
					new Class[] { String.class, String.class });// String sort,
																// String
			// order
			rtn = (String) method.invoke(acUserService, new Object[] { this.sort,
					this.dir });
			break;
		case ACTION_IS_USER_NAME_EXIST:
			String userName = request.getParameter("userName");
			this.setId(request);
			rtn = acUserService.isUserNameExist(this.id, userName).toString();
			break;
		case ACTION_EDIT_AC_USER_ACTION:
			this.setId(request);
			this.fillIds(request);
			rtn = acUserService.editAcUserAction(this.id, this.ids, request.getParameter("isValid"), request.getParameter("isMacEnable"));
			break;
		case ACTION_GET_AC_USER_ACTION_FILTERS:
			this.setId(request);
			this.setPaginationParam(request);
			this.setFilterParam(request);
			rtn = acUserService.getAcUserActoinFilter(this.id, sort, dir, filters);
			break;
		case ACTION_DELETE_AC_USER_ACTION:
			this.setId(request);
			rtn = acUserService.deleteAcUserAction(this.id);
			break;
		}

		return rtn;
	}
	
	private void fillObj(HttpServletRequest request) throws Exception{
		AcUser acUser = new AcUser();
		if (ServletFileUpload.isMultipartContent(request)) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(MAX_UPLOAD_FILE_CACHE);
			factory.setRepository(new File(getServletContext().getRealPath(
					UPLOAD_TEMP_DIR)));
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setSizeMax(MAX_UPLOAD_FILE_SIZE);
			
			List<FileItem> items = upload.parseRequest(request);
			for(FileItem item : items){
				String fieldName = item.getFieldName();
				if("id".equals(fieldName)){
					String value = item.getString(Constants.ENCODING);
					if(StringUtils.isEmpty(value)){
						acUser.setId(null);
					}else{
						acUser.setId(Integer.parseInt(value));
					}
				}else if("userName".equals(fieldName)){
					acUser.setUserName(item.getString(Constants.ENCODING));
				}else if("realName".equals(fieldName)){
					acUser.setRealName(item.getString(Constants.ENCODING));
				}else if("userPwd".equals(fieldName)){
					acUser.setUserPwd(item.getString(Constants.ENCODING));
				}else if("ctGender".equals(fieldName)){
					acUser.setCtGender(item.getString(Constants.ENCODING));
				}else if("macAddress".equals(fieldName)){
					acUser.setMacAddress(item.getString(Constants.ENCODING));
				}else if("department".equals(fieldName)){
					acUser.setDepartment(item.getString(Constants.ENCODING));
				}else if("duty".equals(fieldName)){
					acUser.setDuty(item.getString(Constants.ENCODING));
				}else if("mobile".equals(fieldName)){
					acUser.setMobile(item.getString(Constants.ENCODING));
				}else if("tel".equals(fieldName)){
					acUser.setTel(item.getString(Constants.ENCODING));
				}else if("email".equals(fieldName)){
					acUser.setEmail(item.getString(Constants.ENCODING));
				}else if("comment".equals(fieldName)){
					acUser.setComment(item.getString(Constants.ENCODING));
				}else if("photo".equals(fieldName)){
					String photoName;
					Blob photo;
					if(item.getSize() > 0){
						photoName = System.currentTimeMillis() + StringUtils.getFileExtension(item.getName());
						photo = Hibernate.createBlob(item.getInputStream());
						item.write(new File(UPLOAD_TEMP_REAL_DIR + photoName));
					}else{
						photoName = null;
						photo = null;
					}
					acUser.setPhoto(photo);
					acUser.setPhotoName(photoName);
				}
			}
		}
		this.obj = acUser;
	}

}
